package com.appsino.bingluo.secret;


import android.Manifest;
import android.app.ActionBar;
import android.app.AppOpsManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.appsino.bingluo.secret.Utils.MD5;
import com.appsino.bingluo.secret.Utils.StatusBarUtils;
import com.appsino.bingluo.secret.Utils.Utils;
import com.appsino.bingluo.secret.app.BaseActivity;
import com.appsino.bingluo.secret.app.myapplication;
import com.appsino.bingluo.secret.bean.User;
import com.appsino.bingluo.secret.http.BaseCallModel;
import com.appsino.bingluo.secret.http.BaseObserver;
import com.appsino.bingluo.secret.http.HttpLoader;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.bgabanner.BGABanner;
import cn.bingoogolapple.bgabanner.BGALocalImageSize;

public class MainActivity extends BaseActivity {
    private int MY_PERMISSIONS_ALERT = 1010;
    private int CHECKPRESSMISSON_CODE = 1011;
    private static Boolean isExit = false;
    ClipyToastBroadcast broadcast;
    BGABanner bgaBanner;
    private String userid;
    @BindView(R.id.tv_main_feedback)
    TextView feedback;
    @BindView(R.id.tv_main_share)
    TextView share;
    @BindView(R.id.btn_openserver)
    Button btnserver;

    /**
     * 设置布局
     * @return
     */
    @Override
    public int getViewId() {
        return R.layout.activity_main;
    }

    /**
     * 初始化数据
     * @param savedInstanceState
     */
    @Override
    public void init(Bundle savedInstanceState) {
        StatusBarUtils.with(MainActivity.this).init();
        bgaBanner = findViewById(R.id.banner_guide);
        //        boolean canInstall = getPackageManager().canReques
        BGALocalImageSize localImageSize = new BGALocalImageSize(720, 1280, 320, 640);
        //设置数据源
        bgaBanner.setData(localImageSize, ImageView.ScaleType.CENTER_CROP,
                R.drawable.bg_main_bottom_f,
                R.drawable.bg_main_bottom_s,
                R.drawable.bg_main_bottom_t);
    }

    @OnClick({R.id.tv_main_feedback, R.id.tv_main_share, R.id.btn_openserver})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_main_feedback:
                showQuestion();
                break;
            case R.id.tv_main_share:
                Utils.ToastSign(MainActivity.this,"share");
                break;
            case R.id.btn_openserver:
                //判断悬浮窗权限是否开启
//                createNotificationChannel();
                if(myapplication.SERVICEOPEN==false){
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (!Settings.canDrawOverlays(MainActivity.this)) {
                            showLivingDialog();
                        }else{
                          AppOpsManager appOpsMgr = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
                          int mode = appOpsMgr.checkOpNoThrow("android:system_alert_window", android.os.Process.myUid(), getPackageName());
                          Log.d("TAG", "android:system_alert_window: mode=" + mode);
                          //进行授权提示 1006为返回标识
                          if(mode==2){
                              showLivingDialog();
                          }else{
                              openService();
                          }
                        }
                    }else{
                        openService();
                    }
                }else{
                   stopService();
                }

                break;
        }
    }

    /**
     * 开启后台运行服务，监听剪贴板
     * 先进行登陆操作
     * 如果登陆成功开启服务
     * 登陆失败返回错误信息
     */
    public void openService(){
        if (!Utils.isNetworkConnected(this)) {
            Utils.ToastSign(this,"请开启网络连接以使用加密功能");
            return;
        }
        HttpLoader loader = new HttpLoader(MainActivity.this);
        loader.HttpLogin(MD5.getMD5("123456")).subscribe(new BaseObserver<User>() {
            @Override
            public void onSuccess(BaseCallModel<User> response) {
                Log.i("tag", "==============params" + response);
                if (response.getCode() == 0) {
                    userid = response.getData().userID;
                    Intent intenthome = new Intent(Intent.ACTION_MAIN);
                    intenthome.addCategory(Intent.CATEGORY_HOME);
                    startActivity(intenthome);
                    myapplication.SERVICEOPEN = true;
                    IntentFilter intentFilter = new IntentFilter();
                    intentFilter.addAction(ClipyToastBroadcast.Action_Name);
                    broadcast = new ClipyToastBroadcast();
                    registerReceiver(broadcast, intentFilter);
                    Intent mMonitorService = new Intent(MainActivity.this, ClipyService.class);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        startForegroundService(mMonitorService);
                    } else {
                        startService(mMonitorService);
                    }
                    btnserver.setBackgroundResource(R.drawable.btn_main_start);
                }else if(response.getCode()==1003){
                    Utils.ToastSign(MainActivity.this, "版本过旧，需更新后使用");
                }else{
                    Utils.ToastSign(MainActivity.this, "网络繁忙请稍后再试");
                }

            }
            @Override
            public void onFailure(int code, String message) {
                super.onFailure(code, message);
                Utils.ToastSign(MainActivity.this, "网络繁忙请稍后再试");
                Log.i("tag", "==============params fail" + message);
                //                Utils.ToastSign(activity,message);
            }
        });
    }

    /**
     * 停止后台运行服务，停止监听剪贴板
     */
    public void stopService(){
        myapplication.SERVICEOPEN=false;
        unregisterReceiver(broadcast);
        Intent intent = new Intent(MainActivity.this, ClipyService.class);
        stopService(intent);
        btnserver.setBackgroundResource(R.drawable.btn_main_unstart);
    }

    /**
     * 悬浮窗权限提示框
     */
    private void showLivingDialog(){
        Dialog dialog;
        dialog = new Dialog(this,R.style.myDialog);
        dialog.setContentView(R.layout.permission_alert_pop);
        dialog.findViewById(R.id.iv_pop_toclose).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.findViewById(R.id.btn_pop_toset).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivity(intent);
            }
        });
        dialog.show();
    }

    /**
     * 反馈弹出框
     */
    /**
     * 悬浮窗权限提示框
     */
    private void showQuestion(){
        Dialog dialog;
        dialog = new Dialog(this,R.style.myDialog);
        dialog.setContentView(R.layout.question_alert_pop);
        dialog.findViewById(R.id.iv_question_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        EditText editText = dialog.findViewById(R.id.et_question_msg);
        dialog.findViewById(R.id.btn_pop_submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String msg = editText.getText().toString().trim();
                if(TextUtils.isEmpty(msg)){
                    Utils.ToastSign(MainActivity.this,"反馈的内容不能为空");
                }else{
                    feedback(msg);
                    dialog.dismiss();
                }
            }
        });
        dialog.show();
    }

    /**
     * 页面销毁的时候，关闭广播
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopService();
    }

    /**
     * 问题反馈请求
     */
    public void feedback(String msg){
        msg = msg +"-该消息来自加密聊天，请勿回复";
        HttpLoader httpLoader = new HttpLoader(MainActivity.this);
        httpLoader.HttpUs(userid,msg,"0").subscribe(new BaseObserver() {
            @Override
            public void onSuccess(BaseCallModel response) {
                if(response.getCode()==0){
                    Utils.ToastSign(MainActivity.this,"消息反馈成功");
                }
            }

            @Override
            public void onFailure(int code, String message) {
                super.onFailure(code, message);

            }
        });
    }
    /**
     *创建通知渠道
     */
    private void createNotificationChannel() {
        Intent intenthome = new Intent(Intent.ACTION_MAIN);
        intenthome.addCategory(Intent.CATEGORY_HOME);
        startActivity(intenthome);
        IntentFilter intentFilter = new IntentFilter();
        // 2. 设置接收广播的类型
        intentFilter.addAction(TestReveiver.EEEEE);// 只有持有相同的action的接受者才能接收此广播
        // 3. 动态注册：调用Context的registerReceiver（）方法
        TestReveiver broadcast = new TestReveiver();
        registerReceiver(broadcast, intentFilter);
        // 在API>=26的时候创建通知渠道
        Log.i("tag", "启动前台服务  onCreate11111");
        Intent mMonitorService = new Intent(MainActivity.this, MonitorService.class);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            startForegroundService(mMonitorService);
//        } else {
        startService(mMonitorService);
//        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    /**
     * 退出app方法
     */
    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            Utils.ToastSign(this,"再按一次退出app");
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
//            AppManager.getAppManager().finishAllActivity();
//            System.exit(0);
            MainActivity.this.finish();
        }
    }
}
